package com.logic.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jakewharton.rxbinding3.view.RxView;
import com.logic.idevice.IUHFSetting;
import com.logic.idevice.impl.di.SettingsDi;
import com.sinopec.basemodule.BaseApplication;
import com.sinopec.basemodule.base.BaseActivity;
import com.sinopec.basemodule.base.BasePresenter;
import com.sinopec.basemodule.base.CustomToolbar;
import com.sinopec.basemodule.utils.ARouterManagerUtils;
import com.sinopec.basemodule.utils.PhoneUtils;
import com.sinopec.basemodule.utils.PopUtils;
import com.sinopec.basemodule.utils.ToastUtils;
import com.sinopec.basemodule.utils.kotlin.IntEKt;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.uhf.uhf.R;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import kotlin.Unit;

/**
 * 类描述：uhf 设置界面 <br/>
 * 创建人：lwj<br/>
 */
@Route(path = ARouterManagerUtils.GOTO_UHF_SET_ACTIVITY)
public class UhfSetActivity extends BaseActivity<BasePresenter> {
    /**
     * 功率设置seekBar
     */
    private SeekBar mSeekBar;

    /**
     * create by lwj at 2022/7/25
     * 特殊布局
     */
    private FrameLayout flSpecialView;

    /**
     * 功率设置提示文本
     */
    private TextView mSeekBarHintTv;
    /**
     * 软件提示音开关
     */
    private Switch mHintSingSwitch;
    /**
     * 设备id
     */
    private TextView mDeviceIdTv;
    /**
     * 账户
     */
    private TextView mAccountNumberTv;
    /**
     * app版本号布局
     */
    private LinearLayout mAppVersionLl;
    /**
     * app版本号
     */
    private TextView mAppVersionTv;
//    /**
//     * 设置按钮
//     */
//    private TextView mSetTv;
    /**
     * 退出登录
     */
    private TextView mLoginOutTv;

    private PublishSubject<Integer> mPs = PublishSubject.create();
    private IUHFSetting setting = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        initPowerObservable();
        super.onCreate(savedInstanceState);
    }

    private void initPowerObservable() {
        addDisposable(mPs.debounce(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(pow -> {
                    //保存功率
                    setting.save(pow, mHintSingSwitch.isChecked());
                }));
    }

    private void refreshDeviceId() {
        addDisposable(new RxPermissions(UhfSetActivity.this)
                .request(Manifest.permission.READ_PHONE_STATE)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        @SuppressLint("MissingPermission")
                        String deviceId = PhoneUtils.getDeviceId();
                        mDeviceIdTv.setText(deviceId);
                    } else {
                        ToastUtils.showToast("请允许获取手机读取权限！");
                    }
                }));
    }

    /**
     * 刷新提示音
     */
    private void refreshSingSwitch() {
        if (!setting.openVoince()) {
            mHintSingSwitch.setChecked(false);
        } else {
            mHintSingSwitch.setChecked(true);
        }
    }

    private void initSeekBar() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_rfid_sb);
        Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, IntEKt.dp2px(30), IntEKt.dp2px(30), true);
        BitmapDrawable thumb = new BitmapDrawable(getResources(), newBitmap);
        mSeekBar.setThumb(thumb);

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mSeekBarHintTv.getLayoutParams();
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                double value = ((float) mSeekBar.getWidth() / 30.0) * (float) 0.75;
                long moveStep = Math.round(value);
                layoutParams.leftMargin = (int) (progress * moveStep);
                mSeekBarHintTv.setLayoutParams(layoutParams);
                mSeekBarHintTv.setText(progress + "dBm");

                mPs.onNext(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setting = SettingsDi.INSTANCE.inject(this, (pow) -> {
            mSeekBar.setProgress(pow);
            mSeekBarHintTv.setText(pow + "dBm");
            return Unit.INSTANCE;
        }, (temp) -> {
            return Unit.INSTANCE;
        });
        setting.init(this, getLifecycle());

        mSeekBar = findViewById(R.id.seek_bar);
        flSpecialView = findViewById(R.id.flSpecialView);
        mSeekBarHintTv = findViewById(R.id.seek_bar_hint_tv);
        mHintSingSwitch = findViewById(R.id.hint_sing_switch);
        mDeviceIdTv = findViewById(R.id.device_id_tv);
        mAccountNumberTv = findViewById(R.id.account_number_tv);
        mAppVersionLl = findViewById(R.id.app_version_ll);
        mAppVersionTv = findViewById(R.id.app_version_tv);
        //mSetTv = findViewById(R.id.set_tv);
        mLoginOutTv = findViewById(R.id.login_out_tv);

        setting.specialUi(flSpecialView);

        //设置用户信息
        mAccountNumberTv.setText(BaseApplication.getInstance().getUserManager().getUserName());

        //设置版本号
        mAppVersionTv.setText(BaseApplication.getInstance().getVersionName());

        //初始化功率设置
        initSeekBar();

        addDisposable(Observable
//                .interval(200, 100, TimeUnit.MILLISECONDS)
                .just(0L, 1L)
                .delay(new Function<Long, ObservableSource<Long>>() {
                    @Override
                    public ObservableSource<Long> apply(Long aLong) throws Exception {
                        if (aLong == 0) {
                            return Observable.timer(200, TimeUnit.MILLISECONDS);
                        }
                        return Observable.timer(400, TimeUnit.MILLISECONDS);
                    }
                })
                .take(2)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (aLong == 0) {
                            //获取设备功率
                            setting.refreshPower();
                        } else {
                            //获取设备温度
//                            readTemperature();
                        }
                    }
                }));
        //刷新软件提示音开关
        refreshSingSwitch();
        //刷新设备id
        refreshDeviceId();
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        mHintSingSwitch.setOnCheckedChangeListener((btn, isSelected) -> {
            setting.save(mSeekBar.getProgress(), isSelected);
        });

        /**
         * 检查更新
         */
        addDisposable(RxView.clicks(mAppVersionLl)
                .throttleFirst(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(unit -> {
                    //BaseApplication.getInstance().appUpdateEvent(true);
                })
        );

        /**
         * 退出登录
         */
        addDisposable(RxView.clicks(mLoginOutTv)
                .throttleFirst(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(unit -> {
                    PopUtils.showExitPopWindow(mContext, new PopUtils.PopClickListener() {
                        @Override
                        public void onItem1Click() {
                        }

                        @Override
                        public void onItem2Click() {
                            ARouterManagerUtils.gotoLogin();
                            BaseApplication.getInstance().exit();
                            mContext.finish();
                        }
                    });
                })
        );

    }

    @Override
    public void configToolbar(CustomToolbar rToolbar) {
        rToolbar.setTitle("设置")
                .setElevation(0f);
    }

    @Override
    public int getContentView() {
        return R.layout.bm_f_uhf_set;
    }
}
